<!-- /*
*@Description: 活码数据分析
*@MethodAuthor:  shenmengfei_sinosoft
*@Date: 2023-05-25 09:59:18
*/ -->
<template>
  <div class="verbal-wrap">
    <div class="page-content">
      <div v-loading="pageLoading" class="content-group">
        <el-tabs v-model="tabsType" @tab-click="handleTabChange">
          <el-tab-pane label="渠道活码" name="0"></el-tab-pane>
          <el-tab-pane label="群活码" name="1"></el-tab-pane>
        </el-tabs>
        <div class="group-title">
          <div class="title-name" @click="handleClickAll">
            <i :class="[ 'el-icon-caret-bottom', iconRotate ? 'icon-rotate-90' : 'icon-rotate-0' ]" style="color:#ccc"></i>全部
          </div>
        </div>
        <div :class="iconRotate ? 'group-name' : 'group-name-unfold'">
          <div v-for="item in groupList" :key="item.id" :class="[ 'group-title', 'group-item', { 'group-item-active': currentGroupIndex === item.id } ]"
            @click="switchGroup(item.id, item)">
            <div class="item-name">{{ item.name }}</div>
          </div>
        </div>
      </div>
      <div class="content-table">
        <div style="border-left: 1px solid #f1f1f1; padding: 16px 15px 20px 15px;">
          <div style="border-bottom: 1px solid #eee">
            <NormalForm :pageTitle="pageTitle" :isShowCard="false" :operateForm="queryForm" :formList="formList" @handleQuery="handleQuery" @handleReset="handleReset"></NormalForm>
          </div>
          <div style="text-align: right; margin: 20px 0;">
            <el-button v-hasPermi="['admin:code:add']" type="primary" @click="downloadFn()">导出Excel</el-button>
          </div>
          <div>
            <el-table ref="activeAnalysisTable" v-loading="tableLoading" :data="activeAnalysisList" :row-style="{ height: '40px' }" height="260px" @select-all="handleSelectedCancel" @select="handleSelectionChange" :row-key="(row) => { return row.id }">
              <el-table-column type="selection" width="60" :reserve-selection="true"></el-table-column>
              <el-table-column align="center" label="序号" type="index" width="50"></el-table-column>
              <el-table-column key="codeName" align="center" label="名称" prop="codeName" show-overflow-tooltip></el-table-column>
              <el-table-column key="addCustomer" align="center" :label="tabsType == '0' ? '今日添加客户数（人）' : '今日加群人数（人）'" prop="addCustomer"></el-table-column>
              <el-table-column key="lostCustomer" align="center" :label="tabsType == '0' ? '今日流失客户数（人）' : '今日退群人数（人）'" prop="lostCustomer"></el-table-column>
              <el-table-column key="addAll" align="center" :label="tabsType == '0' ? '总添加客户数（人）' : '总加群人数（人）'" prop="addAll" show-overflow-tooltip></el-table-column>
              <el-table-column key="lostAll" align="center" :label="tabsType == '0' ? '总流失客户数（人）' : '总退群人数（人）'" prop="lostAll" show-overflow-tooltip></el-table-column>
            </el-table>
            <NormalPagination :currentPage="queryForm.pageNum" :pageSize="queryForm.pageSize" :total="total" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange"></NormalPagination>
            <div v-show="isShowEchart" class="analysis-echart">
              <div class="analysis-echart-title">
                <div class="title-icon"></div>
                <div class="title-text">图表数据</div>
              </div>
              <div class="analysis-echart-content">
                <el-form class="echarts-search" ref="echartsForm" :model="echartsForm">
                  <el-form-item>
                    <el-select v-model="echartsForm.dateType" @change="typeChangeDate($event)" style="width: 120px;">
                      <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item>
                    <template v-if="echartsForm.dateType === 'DAY'">
                      <el-date-picker key="d" v-model="echartsForm.dateList" type="daterange" :clearable="false" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 280px;" @change="getActiveAnalysisEchartDataFn" value-format="yyyy-MM-dd" :picker-options="pickerOptions"></el-date-picker>
                    </template>
                    <template v-else-if="echartsForm.dateType === 'MONTH'">
                      <el-date-picker key="m" v-model="echartsForm.dateList" type="monthrange" :clearable="false" range-separator="至" start-placeholder="开始月份" end-placeholder="结束月份" style="width: 280px;" @change="getActiveAnalysisEchartDataFn" value-format="yyyy-MM" :picker-options="pickerOptions"></el-date-picker>
                    </template>
                    <template v-else>
                      <el-date-picker key="y1" v-model="echartsForm.dateList[0]" type="year" :clearable="false" style="width: 120px;" @change="startYearChange" value-format="yyyy" :picker-options="pickerOptions"></el-date-picker>
                      <span style="margin: 0 10px;">至</span>
                      <el-date-picker key="y2" v-model="echartsForm.dateList[1]" type="year" :clearable="false" style="width: 120px;" @change="endYearChange" value-format="yyyy" :picker-options="pickerOptions"></el-date-picker>
                    </template>
                  </el-form-item>
                  <el-form-item v-if="tabsType == '0'">
                    <el-select v-model="echartsForm.userId" placeholder="请选择员工" :clearable="true" @change="getActiveAnalysisEchartDataFn">
                      <el-option v-for="item in agentList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item v-else>
                    <el-input v-model="currentAgent" :disabled="true"></el-input>
                  </el-form-item>
                </el-form>
                <div id="echarts-line-father">
                  <div id="echarts-line"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getGroupList, getActiveAnalysisList, getActiveAnalysisEchartData, getEchartUserList } from '@/api/operate/verbalTrick'
import { downLoadFile } from "@/utils/common";
import { formatDate } from '@/utils/validate'

export default {
  data() {
    return {
      tabsType: '0',
      pageTitle: '渠道活码',
      iconRotate: false,
      pageLoading: false,
      groupList: [],
      currentGroupIndex: '',
      currentGroup: '',
      queryForm: {
        name: '',
        deptId: null,
        createId: '',
        pageNum: 1,
        pageSize: 20,
      },
      formList: [
        {
          label: '活码名称',
          value: '',
          prop: 'name',
          type: 'INPUT',
          emunName: ''
        },
        {
          label: '管理机构',
          value: null,
          prop: 'deptId',
          type: 'MANAGE_COM',
          emunName: ''
        },
        {
          label: '创建人',
          value: '',
          prop: 'createId',
          type: 'STAFF',
          emunName: ''
        },
      ],
      total: 0,
      tableLoading: false,
      activeAnalysisList: [],
      // 图表附加查询条件
      echartsForm: {
        dateType: 'DAY',
        dateList: [
          formatDate(new Date(), 'yyyy-MM-dd'),
          formatDate(new Date(), 'yyyy-MM-dd'),
        ],
        userId: '',
      },
      typeList: [
        { label: '按天', value: 'DAY' },
        { label: '自然月', value: 'MONTH' },
        { label: '自然年', value: 'YEAR' },
      ],
      agentList: [],
      currentSid: '',
      currentRow: null,
      currentAgent: '',
      isShowEchart: false,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e7
        }
      },
    }
  },
  mounted() {
    this.handleGetGroupList();
    this.handleQuery();
  },
  methods: {
    // 群活码与渠道活码切换
    handleTabChange(e) {
      this.pageTitle = e.index == '0' ? '渠道活码' : '群活码'
      this.currentGroupIndex = ''
      this.currentGroup = null
      this.handleGetGroupList()
      this.handleReset()
    },
    handleClickAll() {
      this.iconRotate = !this.iconRotate
      if (this.iconRotate) {
        this.handleTabChange({ index: this.tabsType })
      }
    },
    handleGetGroupList() {
      const params = {
        levelType: 3,
        tabsType: this.tabsType,
        mediaType: +this.tabsType + 1,
      }
      this.pageLoading = true
      getGroupList(params).then((res) => {
        this.pageLoading = false
        if (res.code === 200) {
          this.groupList = res.data || []
        }
      }).catch(() => {
        this.pageLoading = false
      })
    },
    handleQuery() {
      this.queryForm.pageNum = 1;
      this.getActiveAnalysisListFn()
    },
    getActiveAnalysisListFn() {
      this.tableLoading = true;
      const params = {
        flag: this.tabsType,
        groupId: this.currentGroupIndex,
        name: this.queryForm.name,
        createId: this.queryForm.createId + '',
        deptId: this.queryForm.deptId,
        pageNum: this.queryForm.pageNum,
        pageSize: this.queryForm.pageSize,
      }
      getActiveAnalysisList(params).then(res => {
        if (res.code == 200) {
          this.activeAnalysisList = res.rows || [];
          this.total = res.total;
        }
        this.tableLoading = false;
        if (this.activeAnalysisList.length > 0) {
          this.isShowEchart = true
          this.handleSelectionChange()
        } else {
          this.isShowEchart = false;
        }
      })
    },
    handleReset() {
      this.queryForm = {
        name: '',
        deptId: null,
        createId: '',
        pageNum: 1,
        pageSize: 20,
      }
      this.$refs.activeAnalysisTable.clearSelection();
      this.getActiveAnalysisListFn()
    },
    // 翻页
    handleSizeChange(val) {
      this.queryForm.pageNum = 1
      this.queryForm.pageSize = val
      this.getActiveAnalysisListFn()
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum = val
      this.getActiveAnalysisListFn()
    },
    // 选择分组
    switchGroup(key, item) {
      if (this.currentGroupIndex === key) return
      this.currentGroupIndex = key
      this.currentGroup = item
      this.handleQuery()
    },
    // 展示图表-默认展示第一条
    handleSelectionChange(val, row) {
      // console.log('当前选择：', val, row)
      let data = null;
      if (row) {
        data = row;
        this.$refs.activeAnalysisTable.clearSelection();
        this.currentSid = data.id;
        this.$refs.activeAnalysisTable.toggleRowSelection(data, true);
      } else {
        data = this.activeAnalysisList[0];
        this.currentSid = data.id;
        this.$refs.activeAnalysisTable.clearSelection();
        this.$refs.activeAnalysisTable.toggleRowSelection(data, true);
      }
      if (this.tabsType == '0') {
        this.getEchartUserListFn();
      } else {
        this.echartsForm.userId = data.userId;
        this.currentAgent = data.userName;
      }
      this.typeChangeDate('DAY');
      this.echartsForm.userId = ''
    },
    handleSelectedCancel() {
      this.$refs.activeAnalysisTable.clearSelection();
      this.$refs.activeAnalysisTable.toggleRowSelection(this.activeAnalysisList[0], true);
    },
    getEchartUserListFn() {
      getEchartUserList({ sid: this.currentSid }).then(res => {
        if (res.code == 200) {
          this.agentList = [];
          res.data.forEach(item => {
            this.agentList.push({ label: item.userName, value: item.userId });
          })
        }
      })
    },
    getActiveAnalysisEchartDataFn() {
      let params = {
        sid: this.currentSid,
        trackTag: this.tabsType,
        userId: this.echartsForm.userId,
        dateType: this.echartsForm.dateType,
        startDate: this.echartsForm.dateList[0],
        endDate: this.echartsForm.dateList[1],
      }
      getActiveAnalysisEchartData(params).then(res => {
        if (res.code == 200) {
          this.initEcharts(res.data.allNum || [],res.data.newNum || [],res.data.lostNum || [],res.data.theDate || [])
        }
      })
    },
    // 导出
    downloadFn() {
      const params = {
        flag: this.tabsType,
        groupId: this.currentGroupIndex,
        name: this.queryForm.name,
        createId: this.queryForm.createId + '',
      }
      downLoadFile('/admin/weGroupCodeRecord/export', params, '活码列表.xlsx')
    },
    // 图表操作
    typeChangeDate(e) {
      if (e == 'DAY') {
        this.echartsForm.dateList = [
          formatDate(new Date(Date.now() - 8.64e7), 'yyyy-MM-dd'),
          formatDate(new Date(Date.now() - 8.64e7), 'yyyy-MM-dd'),
        ]
      }
      if (e == 'MONTH') {
        this.echartsForm.dateList = [
          formatDate(new Date(Date.now() - 8.64e7), 'yyyy-MM'),
          formatDate(new Date(Date.now() - 8.64e7), 'yyyy-MM'),
        ]
      }
      if (e == 'YEAR') {
        this.echartsForm.dateList = [
          formatDate(new Date(Date.now() - 8.64e7), 'yyyy'),
          formatDate(new Date(Date.now() - 8.64e7), 'yyyy'),
        ]
      }
      this.getActiveAnalysisEchartDataFn();
    },
    // 日期选择
    startYearChange(val) {
      if (val > this.echartsForm.dateList[1]) {
        this.$message.error('起始年不能大于结束年！');
      } else {
        this.getActiveAnalysisEchartDataFn();
      }
    },
    endYearChange(val) {
      if (val < this.echartsForm.dateList[0]) {
        this.$message.error('结束年不能小于起始年！');
      } else {
        this.getActiveAnalysisEchartDataFn();
      }
    },
    initEcharts(allNums, addNums, plusNums, dateList) {
      let legendX = ['客户总数', '新增人数', '流失人数'];
      let legendY = ['进群总数', '新增进群人数', '退群人数'];
      let legendData = this.tabsType == '0' ? legendX : legendY;
      let chartDom = document.getElementById('echarts-line')
      let chartFather = document.getElementById('echarts-line-father')
      chartFather.style = 'overflow-x: scroll;'
      if (dateList.length > 10){
        chartDom.style.width = 100 * dateList.length + 'px'
      } else {
        chartDom.style.width = '100%'
      }
      let myChart = echarts.init(chartDom)
      let option = {
        color: ['#FFAE35', '#69BBC4', '#3CBDFF'],
        tooltip: {
          trigger: 'axis',
        },
        legend: {
          data: legendData,
        },
        grid: {
          left: '10px',
          right: '40px',
          bottom: '20px',
          containLabel: true,
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dateList,
          axisLabel: {
            interval: 2
          },
        },
        yAxis: {
          type: 'value',
          max: 100,
          min: 0,
        },
        series: [
          {
            name: legendData[0],
            type: 'line',
            data: allNums,
          },
          {
            name: legendData[1],
            type: 'line',
            data: addNums,
          },
          {
            name: legendData[2],
            type: 'line',
            data: plusNums,
          },
        ],
      }

      option && myChart.setOption(option)
      myChart.resize();
    },
  },
}
</script>

<style lang="scss" scoped>
@import '@/styles/base.scss';
.verbal-wrap {
  background: #fff;
  padding: 0;
  height: 100%;
  .page-content {
    display: flex;
    height: calc(100% - 20px);
    margin-left: 24px;
    .content-group {
      width: 200px;
      padding: 12px 15px 0 0;
      font-size: 12px;
      .group-title {
        height: 37px;
        display: flex;
        align-items: center;
        cursor: pointer;
        i {
          margin-right: 5px;
        }
        .title-name {
          flex: 1;
          .icon-rotate-90 {
            transition: transform 0.2s, -webkit-transform 0.2s;
            transform: rotateZ(-90deg);
            color: #C0C4CC;
          }
          .icon-rotate-0 {
            transition: transform 0.2s, -webkit-transform 0.2s;
            transform: rotate(0deg);
            color: #C0C4CC;
          }
        }
      }
      .group-name {
        max-height: 0;
        overflow: hidden;
      }
      .group-name-unfold {
        max-height: calc(100% - 30px);
        transition: max-height 0.3s;
        padding: 0 10px 0 20px;
        overflow: scroll;
        &::-webkit-scrollbar {
          width: 0;
        }
        -ms-overflow-style: none;
        overflow: -moz-scrollbars-none;
      }
      .group-item-active {
        background-color: #fff2ee;
      }
    }
    .content-table {
      width: calc(100% - 200px);
      .analysis-echart {
        margin-bottom: 20px;
        .analysis-echart-title {
          display: flex;
          align-items: center;
          margin: 20px 0;
          .title-icon {
            width: 4px;
            height: 24px;
            background: rgba(15, 64, 245, 1);
            margin-right: 10px;
          }
          .title-text {
            color: rgba(16, 16, 16, 1);
            font-size: 16px;
            font-family: SourceHanSansSC-regular;
          }
        }
        .analysis-echart-content {
          box-sizing: border-box;
          height: 460px;
          padding: 0 20px 40px 0;
          .echarts-search {
            display: flex;
            margin-bottom: 10px;
          }
          #echarts-line {
            width: 100%;
            height: 420px;
          }
        }
      }
    }
  }
}
</style>
